package com.hskn.hss.module.outstorageCfg.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hskn.hss.core.utils.LoginUtils;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.materialAppli.entity.TlMaterialApplication;
import com.hskn.hss.module.materialAppli.mapper.TlMaterialApplicationMapper;
import com.hskn.hss.module.materialDetail.entity.TlMaterialDetail;
import com.hskn.hss.module.materialDetail.service.ITlMaterialDetailService;
import com.hskn.hss.module.outstorageCfg.entity.TlOutStorageCfg;
import com.hskn.hss.module.outstorageCfg.mapper.TlOutStorageCfgMapper;
import com.hskn.hss.module.outstorageCfg.service.ITlOutStorageCfgService;
import com.hskn.hss.module.storageDetail.entity.TlStorageDetail;
import com.hskn.hss.module.storageDetail.mapper.TlStorageDetailMapper;
import com.hskn.hss.module.storageDetail.service.ITlStorageDetailService;
import com.hskn.hss.module.userdepart.mapper.SysUserDepartMapper;
import com.hskn.hss.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hskn
 * @since 2021-05-10
 */
@Service
public class TlOutStorageCfgServiceImpl extends ServiceImpl<TlOutStorageCfgMapper, TlOutStorageCfg> implements ITlOutStorageCfgService {

    @Resource
    TlOutStorageCfgMapper tlOutStorageCfgMapper;
    @Resource
    SysUserDepartMapper sysUserDepartMapper;
    @Autowired
    ITlMaterialDetailService tlMaterialDetailService;
    @Resource
    TlMaterialApplicationMapper tlMaterialApplicationMapper;
    @Autowired
    ITlStorageDetailService tlStorageDetailService;
    @Resource
    TlStorageDetailMapper tlStorageDetailMapper;

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class}) //添加事务
    public AjaxResult insert(JSONObject params) {

        TlOutStorageCfg tlOutStorageCfg = params.getObject("data", TlOutStorageCfg.class);
        int i = tlOutStorageCfgMapper.insert(tlOutStorageCfg);
        boolean flag = i > 0 ? true : false;
        if (flag) {
            return AjaxResult.success("操作成功");
        } else {
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class}) //添加事务
    public AjaxResult update(JSONObject params) {
        try {
            String uid = LoginUtils.getUser().getUid();
            String id = params.getString("id");
            String remark = params.getString("remark");
            String recivetype = params.getString("recivetype");
            TlOutStorageCfg tlOutStorageCfg = tlOutStorageCfgMapper.selectById(id);
            tlOutStorageCfg.setStatus("1");
            tlOutStorageCfg.setReciveperson(uid);
            tlOutStorageCfg.setRecivetime(new Date());
            tlOutStorageCfg.setRemark(remark);
            tlOutStorageCfg.setRecivetype(recivetype);

            QueryWrapper<TlMaterialApplication> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(TlMaterialApplication::getSerialnumber, tlOutStorageCfg.getMaterialnumber());
            TlMaterialApplication tlMaterialApplication = tlMaterialApplicationMapper.selectOne(queryWrapper);
            tlMaterialApplication.setStatus("4");
            tlMaterialApplicationMapper.updateById(tlMaterialApplication);//回填 计划表状态

            List<TlMaterialDetail> tlMaterialDetails = tlMaterialDetailService.getitemListBySerialnumber(tlOutStorageCfg.getSerialnumber());
            /**
             * 计入库存，完成入库开始
             */
            for (TlMaterialDetail tlMaterialDetail : tlMaterialDetails) {
                String itemClass = tlMaterialDetail.getItemclass();
                String itemType = tlMaterialDetail.getItemtype();
                int num = tlMaterialDetail.getItemnum();
                Map querymap = new HashMap<>();
                querymap.put("storage_id", tlOutStorageCfg.getStoragecenterid());
                querymap.put("item_class", itemClass);
                querymap.put("item_type", itemType);

                List<TlStorageDetail> tlStorageDetaillist = tlStorageDetailMapper.selectByMap(querymap);
                TlStorageDetail tlStorageDetail = tlStorageDetaillist.get(0);
                int sumNum = tlStorageDetail.getItemNum();
                if (sumNum < num) {
                    return AjaxResult.fail("库存不足");
                }
                tlStorageDetail.setItemNum(sumNum);
                tlStorageDetailMapper.updateById(tlStorageDetail);
            }

            /**
             * 计入库存，完成入库结束
             */
            int i = tlOutStorageCfgMapper.updateById(tlOutStorageCfg);

            return AjaxResult.success("操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败！请稍后再试");
        }


    }

    @Override
    public TlOutStorageCfg getDetailById(JSONObject params) throws HssException {
        String id = params.getString("id");
        TlOutStorageCfg tlOutStorageCfg = tlOutStorageCfgMapper.selectById(id);
        List<TlMaterialDetail> tlMaterialDetails = tlMaterialDetailService.getitemListBySerialnumber(tlOutStorageCfg.getMaterialnumber());
        if (!tlMaterialDetails.isEmpty()) {
            tlOutStorageCfg.setDateils(tlMaterialDetails);
        }
        return tlOutStorageCfg;
    }

    @Override
    public JSONObject getList(JSONObject params) {
        Long page = StringUtils.isEmpty(params.getLong("page")) ? 1 : params.getLong("page");
        Long size = StringUtils.isEmpty(params.getLong("size")) ? 10 : params.getLong("size");
        JSONObject json = new JSONObject();

        Map map = new HashMap();
        map.put("storagecenterid", params.getString("storagecenterid"));
        map.put("reciveperson", params.getString("reciveperson"));
        map.put("serialnumber", params.getString("serialnumber"));
        map.put("starttime", params.getString("starttime"));
        map.put("endtime", params.getString("endtime"));
        map.put("status", params.getString("status"));


        Page<TlOutStorageCfg> outStorageCfgPage = new Page<>(page, size, true);
        IPage<TlOutStorageCfg> iPage = tlOutStorageCfgMapper.listoutstorage(outStorageCfgPage, map);

        json.put("total", iPage.getTotal());
        json.put("size", iPage.getSize());
        json.put("pages", iPage.getPages());
        json.put("current", iPage.getCurrent());
        json.put("outStoragelist", iPage.getRecords());
        return json;
    }

    @Override
    public List<TlOutStorageCfg> getitemListBymaterialnumber(String materialnumber) throws HssException {
        QueryWrapper<TlOutStorageCfg> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TlOutStorageCfg::getMaterialnumber, materialnumber);
        List<TlOutStorageCfg> tlOutStorageCfgList = tlOutStorageCfgMapper.selectList(queryWrapper);
        return tlOutStorageCfgList;
    }
}
